#pragma once
#include"Socket.hpp"
using namespace SocketModule;
//实现回调函数调用上层
using func_t = std::function<void(std::shared_ptr<Socket> sockfd,InetAddr peer)>;
class TcpServe
{
    public:
    TcpServe(uint16_t port,func_t func):_port(port),_func(func),_isrunning(false),_listensocket(std::make_unique<TcpSocket>())
    {

        //此时我们的_listensocket
        _listensocket->BuildTcpSocketMethod(port);

    }
    void Start()
    {
        _isrunning=true;
        while(_isrunning)
        {
            InetAddr client;
            auto lsocket=_listensocket->acceptordie(&client);
            if(lsocket==nullptr)
            {
                LOG(LogLevel::DEBUG)<<"accept warning";
                continue;
            }
            LOG(LogLevel::DEBUG) << "accept success ..." << client.StringAddr();

            //创建子进程
            pid_t id=fork();
            if(id==0)
            {
                //子进程
                //关闭自己的lisetsockfd
                LOG(LogLevel::DEBUG)<<_listensocket->getfd();
                _listensocket->Close();
                if(fork()>0)
                {
                    exit(OK);
                }
                //孙子进程
                _func(lsocket,client);
                exit(OK);

            }
            else if(id>0)
            {
                //父进程
                //关闭自己的sockfd
                //LOG(LogLevel::DEBUG)<<lsocket->getfd();
                lsocket->Close();
                waitpid(id,nullptr,0);
            }
            else
            {
                exit(FORK_ERR);
            }
        }
        _isrunning=false;
    }
    ~TcpServe(){}
    private:
    std::unique_ptr<Socket> _listensocket;
    uint16_t _port;
    func_t _func;
    bool _isrunning;
};